package com.justgame.project.base.utils;

import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.constant.Regex;
import com.justgame.project.cloud.common.exception.Exc;
import com.justgame.project.cloud.common.util.AppContextUtils;
import com.justgame.project.cloud.common.util.RedisUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class EmailUtil {

    private static String from;

    /**
     * 使用@Value注入application.properties中指定的用户名
     */
    @Value("${spring.mail.username}")
    private void setFrom(String from) {
        EmailUtil.from = from;
    }

    /**
     * 用于发送文件
     */
    @Resource
    private JavaMailSender mailSender;

    /**
     * HTML模板
     */
    @Resource
    TemplateEngine templateEngine;

    /**
     * 发送纯文本Email
     *
     * @param to      发送到指定的邮箱
     * @param subject 主题
     * @param content 内容
     */
    public static void sendSimpleMail(String to, String subject, String content) {
        JavaMailSender mailSender = AppContextUtils.getBean(JavaMailSender.class);
        SimpleMailMessage message = new SimpleMailMessage();
        //收信人
        message.setTo(to);
        //主题
        message.setSubject(subject);
        //内容
        message.setText(content);
        //发信人
        message.setFrom(from);
        mailSender.send(message);
    }

    public static void success2Sign(String mail, String account) {
        Map<String, Object> data = new HashMap<>();
        data.put("account", account);
        sendHtmlMail(mail, "Just Game 社交型游戏论坛 — 【恭喜您注册成功】", data, "html/SuccessSign/index.html");
    }

    public static void success2ChangeEmail(String mail, String account) {
        Map<String, Object> data = new HashMap<>();
        data.put("account", account);
        data.put("email", mail);
        sendHtmlMail(mail, "Just Game 社交型游戏论坛 — 【邮箱变更成功通知】", data, "html/SuccessChangeEmail/index.html");
    }

    public static void emailHasChanged(String mail, String time) {
        Map<String, Object> data = new HashMap<>();
        data.put("time", time);
        sendHtmlMail(mail, "Just Game 社交型游戏论坛 — 【邮箱变更通知】", data, "html/ChangeEmail/index.html");
    }

    public static void sendMailCode(String mail, String code) {
        Map<String, Object> data = new HashMap<>();
        data.put("code", code);
        sendHtmlMail(mail, "Just Game 社交型游戏论坛 — 【邮箱验证码】", data, "html/SendMailCode/index.html");
    }

    @SneakyThrows
    public static void sendHtmlMail(String to, String subject, Map<String, Object> data, String htmlAddr) {
        JavaMailSender mailSender = AppContextUtils.getBean(JavaMailSender.class);
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        TemplateEngine templateEngine = AppContextUtils.getBean(TemplateEngine.class);
        helper.setSubject(subject);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSentDate(new Date());
        Context context = new Context();
        context.setVariables(data);
        String process = templateEngine.process(htmlAddr, context);
        helper.setText(process, true);
        mailSender.send(mimeMessage);
    }

    /**
     * 检查邮箱验证码是否匹配
     *
     * @param email
     * @param mailCode
     */
    public static void checkMailCode(String email, String mailCode) {
        RedisUtil redisUtil = AppContextUtils.getBean(RedisUtil.class);
        if (StringUtils.isBlank(email)) {
            throw new Exc("邮箱验不能为空！");
        } else if (!Regex.isEmail(email)) {
            throw new Exc("邮箱格式不合规，请重新输入！");
        } else if (StringUtils.isBlank(mailCode)) {
            throw new Exc("邮箱验证码不能为空！");
        }
        /* 判断验证码是否正确 */
        String realMailCode = redisUtil.get(Const.EMAIL_VALIDATION_CODE + email);
        if (StringUtils.isBlank(realMailCode)) {
            throw new Exc("请先获取邮箱验证码！");
        } else if (!realMailCode.equals(mailCode)) {
            throw new Exc("邮箱验证码错误！");
        }
    }

}
